package com.bigknow.appstore.proxy.handler.register;

import com.bigknow.appstore.proxy.cache.ICacheManager;
import com.bigknow.appstore.proxy.enumerate.ErrorType;
import com.bigknow.appstore.proxy.enumerate.ProxyState;
import com.bigknow.appstore.proxy.exceptions.ProxyError;
import com.bigknow.appstore.proxy.exceptions.processor.impl.ErrorAssert;
import com.bigknow.appstore.proxy.handler.base.BaseInboundHandler;
import com.bigknow.appstore.proxy.log.ILogWriter;
import com.bigknow.appstore.proxy.server.IProxyServer;
import com.bigknow.appstore.proxy.util.HandlerVariables;
import com.bigknow.appstore.proxy.util.NameValuePair;
import com.bigknow.appstore.proxy.util.UriAndUrlHelper;
import com.bigknow.appstore.proxy.vo.RequestVo;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpMessage;
import io.netty.handler.codec.http.FullHttpRequest;

import java.net.URI;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

/**
 * 获取用户信息，首先判断cookie中时候有userid信息，如果没有就看
 * uri是否有userId参数，如果有参数还要将参数写入requestVo。
 * Created by chaos on 2016/9/19.
 */
@ChannelHandler.Sharable
public class UserRegistHandler extends BaseInboundHandler {

    public UserRegistHandler(IProxyServer proxyServer, ICacheManager cacheManager, ILogWriter writer) {
        super(proxyServer, cacheManager, writer);
    }

    @Override
    public void read(ChannelHandlerContext ctx, FullHttpMessage msg) throws Exception {
        //测试一下
        //this.proxyServer.setState(ProxyState.PAUSE);
        //if (1 == 1) ErrorAssert.throwError(ctx,ErrorType.REQUEST_DATA_ERROR,null,null);
        //if(!isFullHttpRequestMsg(msg)) return;

        FullHttpRequest request = (FullHttpRequest) msg;
        //添加两个参数
        request.headers().set("Oauth-token-Url", "http://" + proxyServer.getRealServerIp() + ":"
                + proxyServer.getRealAppSysPort() + "/oauth/token");
        request.headers().set("Oauth-code-Url", "http://" + proxyServer.getRealServerIp() + ":"
                + proxyServer.getRealAppSysPort() + "/oauth/code");


        String cookies = request.headers().get("Cookie");
        if (cookies != null) {
            String userId = getUserId(cookies.split(";"));
            RequestVo requestVo = getCurrentRequestVo();
            requestVo.setUserId(userId);
        }
        //将url中的uerId弄出来 url中的userId始终优先
        List<NameValuePair> nps = UriAndUrlHelper.parse(new URI(request.uri()), "utf-8");
        for (NameValuePair np : nps) {
            if (np.getName().equals("userId")) {
                RequestVo requestVo = getCurrentRequestVo();
                requestVo.setUserId(np.getValue());
                setCurrentRequestVo(requestVo);
            }
        }
        ctx.fireChannelRead(msg);
    }

    private String getUserId(String[] cookiesArray) {
        for (String s : cookiesArray) {
            if (s.startsWith("userId=") || s.startsWith(" userId=")) {
                return s.substring(s.indexOf("=") + 1, s.indexOf(";") == -1 ? s.length() : s.indexOf(";"));
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String cookies = "region3_registry_menu=visible; amPt_2132_saltkey=TCu7yZ6G; " +
                "amPt_2132_lastvisit=1474270952; amPt_2132_atarget=1; tMjG_2132_saltkey=lHd5u7N7; " +
                "tMjG_2132_lastvisit=1474444450; Hm_lvt_900a7d14568b09936b1f5d2f3cd062e0=1475027496; " +
                "emstat_bc_emcount=3034225138935480791; st_pvi=24130193333238; " +
                "userId=AXXXXXXXXV; " +
                "Hm_lvt_66e3c8620359585d5d937e5cdfb8e159=1476092417,1476171656,1476172063";
        for (String s : cookies.split(";")) {
            if (s.startsWith("userId=") || s.startsWith(" userId=")) {
                System.out.println(s.substring(s.indexOf("=") + 1, s.indexOf(";") == -1 ? s.length() : s.indexOf(";")));
            }
        }
    }
}
